package api

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto"
	"api-gateway/handler/request"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
)

// 用户注册
func RegisterUser(c *gin.Context) {
	//接受参数
	var req request.RegisterUser
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user, err := config.UserClient.RegisterUser(c, &__.RegisterUserReq{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "用户注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "用户注册成功",
		"data": user.UserId,
	})

}

// 用户登录
func LoginUser(c *gin.Context) {
	//接收参数
	var req request.LoginUser
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	//业务逻辑
	user, err := config.UserClient.LoginUser(c, &__.LoginUserReq{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "用户登录失败",
			"data": nil,
		})
		return
	}
	token, err := gojwt.NewJWT(config.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: uint(user.UserId),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*7,
		},
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "生成token失败",
			"data": nil,
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "用户登录成功",
		"data": token,
	})
}

// 完善用户信息
func PerfectUser(c *gin.Context) {
	//接受参数
	var req request.PerfectUser
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	//业务逻辑
	user, err := config.UserClient.PerfectUser(c, &__.PerfectUserReq{
		UserId:   int64(c.GetUint("userId")),
		Username: req.Username,
		Email:    req.Email,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "用户完善信息失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "用户完善信息成功",
		"data": user.UserId,
	})
}
